import Markdown from '@/components/markdown';
import Back from '@/components/router/Back';
import {
  CopyOutlined,
  EditOutlined,
  EyeOutlined,
  StarFilled,
  StarOutlined,
} from '@ant-design/icons';
import { useSize } from 'ahooks';
import { Button, Divider, Drawer, Input, message, Tag, Tooltip } from 'antd';
import { forwardRef, memo, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import DatasetList from './DatasetList';
import {
  BaseQuestionType,
  FaqDataset,
  FeedbackQuestionType,
  FreqQuestionType,
  HistoryQA,
  SubQuestionType,
  UnknowQuestionType,
} from '@/types/know/know';
import datasetService from '@/api/services/datasetService';
import { useContextSelector } from 'use-context-selector';
import { KnowMarkContext } from '../context';
import { useCopyToClipboard } from '@/hooks/event/use-copy-to-clipboard';
import React from 'react';
import ChatBox from '@/pages/chat/components/ChatBox';
import TestChatBox from './TestChatBox';
import { D } from 'node_modules/@tanstack/react-query-devtools/build/modern/ReactQueryDevtoolsPanel-D9deyZtU';
import { Message } from '@/types/chat';
import dayjs from 'dayjs';
import { removeThinkTags } from '@/utils/common';
import reportService from '@/api/services/reportService';

const { TextArea } = Input;

interface Props {
  q: string;
  a: string;
  step: number;
  status: number;
  setStep: (step: number) => void;
  onIgnore?: () => void;
  onCancel?: () => void;
  data:
  | BaseQuestionType
  | UnknowQuestionType
  | FeedbackQuestionType
  | FreqQuestionType
  | SubQuestionType;
}
// const QAView = ({ q, a, setStep, step, status, onIgnore, onCancel, data, ref }: Props) => {
//   const { copyToClipboard } = useCopyToClipboard();
//   const { selectedDataset, answer, setSelectedDataset, setAnswer, question, setQuestion } =
//     useContextSelector(KnowMarkContext, (s) => s);
//   const [historyOpen, setHistoryOpen] = useState(false);

//   // 搜狗输入法bug，会导致只能输入一个字符，所以这里定义了editAnswer和editQuestion
//   const [editAnswer, setEditAnswer] = useState('');
//   const [editQuestion, setEditQuestion] = useState('');

//   const [previewAnswer, setPreviewAnswer] = useState(false);
//   const [showTestDrawer, setTestDrawer] = useState(false);
//   const [historyMessages, setHistoryMessages] = useState<Message[]>([]);
//   const [qaList, setQaList] = useState<HistoryQA[]>([]);
//   const refs = useRef(null);
//   const size = useSize(refs);

//   const onCopyClicked = (answer: string) => {
//     copyToClipboard(answer);
//     message.success('复制成功');
//   };

//   const answerRender = (answer: string, edit: boolean = true) => {
//     return (
//       <div className="m-5 w-fit rounded-b-2xl rounded-r-2xl bg-white p-4">
//         <Markdown source={answer} />
//         {/* <Divider /> */}
//         <div className="mt-2 flex items-center">
//           <div className="mr-10 text-xs text-[#8e93a4]">本答案由AI生成，请谨慎参考</div>
//           <div className="ml-auto">
//             <Button
//               type="text"
//               icon={<CopyOutlined color="#B4B8C7" />}
//               onClick={() => {
//                 onCopyClicked(answer);
//               }}
//             ></Button>
//             {status === 0 && edit && (
//               <Tooltip title="标注预期答案">
//                 <Button type="text" icon={<StarOutlined />} onClick={() => setStep(2)}></Button>
//               </Tooltip>
//             )}
//             {status === 1 && edit && (
//               <Tooltip title="已标注">
//                 <Button type="text" icon={<StarFilled style={{ color: '#6640FF' }} />}></Button>
//               </Tooltip>
//             )}
//           </div>
//         </div>
//       </div>
//     );
//   };

//   const onEdit = () => {
//     if (data?.annoId) {
//       setEditAnswer(data.annoA!);
//       setEditQuestion(data.annoQ!);
//     }
//     setStep(1);
//   };

//   const getChatId = () => {
//     if (data && 'keyQuestionChatId' in data) {
//       const d = data as BaseQuestionType;
//       return d.keyQuestionChatId;
//     } else {
//       const d = data as SubQuestionType;
//       return d?.chatId;
//     }
//   };

//   const getChatMessage = () => {
//     if (data && 'keyQuestionText' in data) {
//       const d = data as BaseQuestionType;
//       return d.keyQuestionText;
//     } else {
//       const d = data as SubQuestionType;
//       return d?.text;
//     }
//   };

//   const showQaDrawer = async (id: string) => {
//     const response = await reportService.qAList(id);

//     const qaList = response?.list.map((item, index) => {
//       const textContent = item.value
//         .filter((i) => i?.type == 'text')
//         .map((i) => i?.text?.content)
//         .join('\n');
//       return {
//         content: textContent,
//         time: dayjs(item?.time).format('YYYY-MM-DD HH:mm:ss'),
//         obj: item?.obj,
//       };
//     });

//     setQaList(qaList);
//     setHistoryOpen(true);
//   };

//   useEffect(() => {
//     setAnswer(a);
//     setEditAnswer(a);
//   }, [a]);

//   useEffect(() => {
//     setQuestion(q);
//     setEditQuestion(q);
//   }, [q]);

//   return (
//     <div>
//       {step === 0 && (
//         <div ref={refs} style={{ minHeight: '600px' }} className="flex flex-col overflow-hidden">
//           {status !== 4 && status !== 2 && (
//             <div className="flex items-center gap-2">
//               <span>你可以选择</span>
//               {<Button onClick={onEdit}>{status !== 0 ? '修改' : '编辑'}预期问答</Button>}

//               {status === 0 && (
//                 <React.Fragment>
//                   <span>或者</span>
//                   <p className="cursor-pointer underline" onClick={onIgnore}>
//                     忽略该问题，无需标注答案
//                   </p>
//                 </React.Fragment>
//               )}
//               <Button
//                 className="ml-auto mr-8"
//                 onClick={() => {
//                   setTestDrawer(true);
//                 }}
//               >
//                 测试效果
//               </Button>
//             </div>
//           )}

//           <div
//             className="mt-4 h-full flex-1 overflow-auto rounded-lg border-2 border-WhiteSmoke bg-[#FFF] p-4"
//             style={{ maxHeight: 'calc(80vh - 160px)' }}
//           >
//             <div className="flex">
//               <div className="text-[#8C8C8C]">旧问答：</div>
//               <div className="ml-auto mr-2 flex gap-2 text-xs text-[#8C8C8C]">
//                 <span>{data?.roleName}</span>
//                 <span>{dayjs(data?.time || data?.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
//                 <span>提问</span>
//                 {
//                   <span
//                     onClick={() => {
//                       showQaDrawer(data?.chatId ?? data.keyQuestionChatId);
//                     }}
//                     className="cursor-pointer underline"
//                   >
//                     查看上下文
//                   </span>
//                 }
//               </div>
//             </div>
//             <div className="ml-auto w-fit rounded-l-2xl rounded-t-2xl bg-[#6640FF] p-4 text-white">
//               <Markdown source={q} />
//             </div>
//             {answerRender(a)}
//             {data?.annoId && (
//               <div>
//                 <div className="text-[#8C8C8C]">预期问答：</div>
//                 <div className="ml-auto w-fit rounded-l-2xl rounded-t-2xl bg-[#6640FF] p-4 text-white">
//                   <Markdown source={data?.annoQ} />
//                 </div>
//                 {answerRender(data?.annoA ?? '')}
//               </div>
//             )}
//           </div>
//           <Drawer
//             className="know-gov-drawer"
//             title="测试"
//             placement="right"
//             // width={'auto'}
//             width={'50%'}
//             onClose={() => {
//               setTestDrawer(false);
//               setHistoryMessages([]);
//             }}
//             open={showTestDrawer}
//           >
//             <div className="h-full bg-[#edeff7] p-2">
//               <TestChatBox
//                 open={showTestDrawer}
//                 initChatId={getChatId()}
//                 initChatMessage={getChatMessage()}
//               />
//             </div>
//           </Drawer>
//         </div>
//       )}
//       {step === 1 && (
//         <div
//           className="flex flex-col"
//           style={{ width: size?.width, minHeight: size?.height, height: 'auto' }}
//         >
//           <Back onClick={() => setStep(0)} title={`${status !== 0 ? '修改' : '编辑'}预期问答`} />
//           <div className="flex w-full flex-1" style={{ maxHeight: 'calc(80vh - 160px)' }}>
//             {/* <div className="flex w-full flex-1 p-4" style={{ maxHeight: 'calc(80vh - 160px)' }}> */}
//             <div className="flex w-full flex-col gap-4">
//               <div className="flex flex-col gap-2">
//                 <div>问题</div>
//                 <TextArea
//                   className="know-input h-full flex-1"
//                   bordered={false}
//                   value={editQuestion}
//                   onChange={(e) => {
//                     const text = e.target.value;
//                     setQuestion(text);
//                     setEditQuestion(text);
//                   }}
//                 />
//               </div>
//               <div
//                 className="flex h-full flex-col gap-2 overflow-hidden"
//                 style={{ maxHeight: 'calc(80vh - 160px)' }}
//               >
//                 <div className="flex items-center gap-2">
//                   <span>答案</span>
//                   <Tooltip title={previewAnswer ? '编辑答案' : '预览答案'}>
//                     <Button
//                       onClick={() => {
//                         setPreviewAnswer((prev) => !prev);
//                       }}
//                       type="text"
//                       icon={previewAnswer ? <EditOutlined /> : <EyeOutlined />}
//                     ></Button>
//                   </Tooltip>
//                 </div>
//                 {!previewAnswer && (
//                   <TextArea
//                     className="know-input h-full flex-1"
//                     bordered={false}
//                     value={editAnswer}
//                     onChange={(e) => {
//                       const text = e.target.value;
//                       setEditAnswer(text);
//                       setAnswer(text);
//                     }}
//                   />
//                 )}
//                 {previewAnswer && (
//                   <div className="overflow-y-auto p-2">
//                     <Markdown source={answer} />
//                   </div>
//                 )}
//               </div>
//             </div>
//           </div>
//           {/* <Divider /> */}
//         </div>
//       )}
//       {step === 2 && (
//         <div
//           className="flex flex-col"
//           style={{ width: size?.width, minHeight: size?.height, height: 'calc(80vh - 160px)' }}
//         >
//           <Back onClick={() => setStep(1)} title="选择存放位置" />
//           <DatasetList onDatasetChange={setSelectedDataset} />
//           {/* <Divider /> */}
//         </div>
//       )}
//       <Drawer
//         title="上下文"
//         className="know-gov-drawer"
//         placement="right"
//         width={'50%'}
//         onClose={() => {
//           setHistoryOpen(false);
//         }}
//         open={historyOpen}
//       >
//         <div className="mt-4 h-full flex-1 rounded-lg border-2 border-WhiteSmoke bg-[#FFF] p-4">
//           {qaList?.map((qa, index) => (
//             <div key={index}>
//               {qa.obj == 'Human' && (
//                 <div className="ml-auto w-fit rounded-l-2xl rounded-t-2xl bg-[#6640FF] p-4 text-white">
//                   <Markdown source={qa.content} />
//                 </div>
//               )}
//               {qa.obj == 'AI' && <div>{answerRender(removeThinkTags(qa.content), false)}</div>}
//             </div>
//           ))}
//         </div>
//       </Drawer>
//     </div>
//   );
// };

const QAView = forwardRef(
  ({ q, a, setStep, step, status, onIgnore, onCancel, data }: Props, ref) => {
    const { copyToClipboard } = useCopyToClipboard();
    const { selectedDataset, answer, setSelectedDataset, setAnswer, question, setQuestion } =
      useContextSelector(KnowMarkContext, (s) => s);
    const [historyOpen, setHistoryOpen] = useState(false);

    // 搜狗输入法bug，会导致只能输入一个字符，所以这里定义了editAnswer和editQuestion
    const [editAnswer, setEditAnswer] = useState('');
    const [editQuestion, setEditQuestion] = useState('');

    const [previewAnswer, setPreviewAnswer] = useState(false);
    const [showTestDrawer, setTestDrawer] = useState(false);
    const [historyMessages, setHistoryMessages] = useState<Message[]>([]);
    const [qaList, setQaList] = useState<HistoryQA[]>([]);
    const refs = useRef(null);
    const size = useSize(refs);

    const onCopyClicked = (answer: string) => {
      copyToClipboard(answer);
      message.success('复制成功');
    };

    const answerRender = (answer: string, edit: boolean = true) => {
      return (
        <div className="m-5 w-fit rounded-b-2xl rounded-r-2xl bg-white p-4">
          <Markdown source={answer} />
          {/* <Divider /> */}
          <div className="mt-2 flex items-center">
            <div className="mr-10 text-xs text-[#8e93a4]">本答案由AI生成，请谨慎参考</div>
            <div className="ml-auto">
              <Button
                type="text"
                icon={<CopyOutlined color="#B4B8C7" />}
                onClick={() => {
                  onCopyClicked(answer);
                }}
              ></Button>
              {status === 0 && edit && (
                <Tooltip title="标注预期答案">
                  <Button type="text" icon={<StarOutlined />} onClick={() => setStep(2)}></Button>
                </Tooltip>
              )}
              {status === 1 && edit && (
                <Tooltip title="已标注">
                  <Button type="text" icon={<StarFilled style={{ color: '#6640FF' }} />}></Button>
                </Tooltip>
              )}
            </div>
          </div>
        </div>
      );
    };

    const onEdit = () => {
      if (data?.annoId) {
        setEditAnswer(data.annoA!);
        setEditQuestion(data.annoQ!);
      }
      setStep(1);
    };

    useImperativeHandle(ref, () => ({
      onEdit: () => {
        onEdit();
      },
      testResult: () => {
        setTestDrawer(true);
      },
    }));

    const getChatId = () => {
      if (data && 'keyQuestionChatId' in data) {
        const d = data as BaseQuestionType;
        return d.keyQuestionChatId;
      } else {
        const d = data as SubQuestionType;
        return d?.chatId;
      }
    };

    const getChatMessage = () => {
      if (data && 'keyQuestionText' in data) {
        const d = data as BaseQuestionType;
        return d.keyQuestionText;
      } else {
        const d = data as SubQuestionType;
        return d?.text;
      }
    };

    const showQaDrawer = async (id: string) => {
      const response = await reportService.qAList(id);

      const qaList = response?.list.map((item, index) => {
        const textContent = item.value
          .filter((i) => i?.type == 'text')
          .map((i) => i?.text?.content)
          .join('\n');
        return {
          content: textContent,
          time: dayjs(item?.time).format('YYYY-MM-DD HH:mm:ss'),
          obj: item?.obj,
        };
      });

      setQaList(qaList);
      setHistoryOpen(true);
    };

    useEffect(() => {
      setAnswer(a);
      setEditAnswer(a);
    }, [a]);

    useEffect(() => {
      setQuestion(q);
      setEditQuestion(q);
    }, [q]);

    return (
      <>
        {step === 0 && (
          <div ref={refs} style={{ minHeight: '600px' }} className="flex flex-col overflow-hidden">
            {/* {status !== 4 && status !== 2 && (
              <div className="flex items-center gap-2">
                <span>你可以选择</span>
                {<Button onClick={onEdit}>{status !== 0 ? '修改' : '编辑'}预期问答</Button>}

                {status === 0 && (
                  <React.Fragment>
                    <span>或者</span>
                    <p className="cursor-pointer underline" onClick={onIgnore}>
                      忽略该问题，无需标注答案
                    </p>
                  </React.Fragment>
                )}
                <Button
                  className="ml-auto mr-8"
                  onClick={() => {
                    setTestDrawer(true);
                  }}
                >
                  测试效果
                </Button>
              </div>
            )} */}

            <div
              className="mt-4 h-full flex-1 overflow-auto rounded-lg border-2 border-WhiteSmoke bg-[#FFF] p-4"
              style={{ maxHeight: 'calc(80vh - 160px)' }}
            >
              <div className="flex">
                <div className="text-[#8C8C8C]">旧问答：</div>
                <div className="ml-auto mr-2 flex gap-2 text-xs text-[#8C8C8C]">
                  <span>{data?.roleName}</span>
                  <span>{dayjs(data?.time || data?.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
                  <span>提问</span>
                  {
                    <span
                      onClick={() => {
                        showQaDrawer(data?.chatId ?? data.keyQuestionChatId);
                      }}
                      className="cursor-pointer underline"
                    >
                      查看上下文
                    </span>
                  }
                </div>
              </div>
              <div className="ml-auto w-fit rounded-l-2xl rounded-t-2xl bg-[#6640FF] p-4 text-white">
                <Markdown source={q} />
              </div>
              {answerRender(a)}
              {data?.annoId && (
                <div>
                  <div className="text-[#8C8C8C]">预期问答：</div>
                  <div className="ml-auto w-fit rounded-l-2xl rounded-t-2xl bg-[#6640FF] p-4 text-white">
                    <Markdown source={data?.annoQ} />
                  </div>
                  {answerRender(data?.annoA ?? '')}
                </div>
              )}
            </div>
            <Drawer
              className="know-gov-drawer"
              title="测试"
              placement="right"
              // width={'auto'}
              width={'50%'}
              onClose={() => {
                setTestDrawer(false);
                setHistoryMessages([]);
              }}
              open={showTestDrawer}
            >
              <div className="h-full bg-[#edeff7] p-2">
                <TestChatBox
                  open={showTestDrawer}
                  initChatId={getChatId()}
                  initChatMessage={getChatMessage()}
                />
              </div>
            </Drawer>
          </div>
        )}
        {step === 1 && (
          <div
            className="flex flex-col"
            style={{ width: size?.width, minHeight: size?.height, height: 'auto' }}
          >
            {/* <Back onClick={() => setStep(0)} title={`${status !== 0 ? '修改' : '编辑'}预期问答`} /> */}
            <div className="flex w-full flex-1" style={{ maxHeight: 'calc(80vh - 160px)' }}>
              {/* <div className="flex w-full flex-1 p-4" style={{ maxHeight: 'calc(80vh - 160px)' }}> */}
              <div className="flex w-full flex-col gap-4">
                <div className="flex flex-col gap-2">
                  <div>问题</div>
                  <TextArea
                    className="know-input h-full flex-1"
                    bordered={false}
                    value={editQuestion}
                    onChange={(e) => {
                      const text = e.target.value;
                      setQuestion(text);
                      setEditQuestion(text);
                    }}
                  />
                </div>
                <div
                  className="flex h-full flex-col gap-2 overflow-hidden"
                  style={{ maxHeight: 'calc(80vh - 160px)' }}
                >
                  <div className="flex items-center gap-2">
                    <span>答案</span>
                    <Tooltip title={previewAnswer ? '编辑答案' : '预览答案'}>
                      <Button
                        onClick={() => {
                          setPreviewAnswer((prev) => !prev);
                        }}
                        type="text"
                        icon={previewAnswer ? <EditOutlined /> : <EyeOutlined />}
                      ></Button>
                    </Tooltip>
                  </div>
                  {!previewAnswer && (
                    <TextArea
                      className="know-input h-full flex-1"
                      bordered={false}
                      value={editAnswer}
                      onChange={(e) => {
                        const text = e.target.value;
                        setEditAnswer(text);
                        setAnswer(text);
                      }}
                    />
                  )}
                  {previewAnswer && (
                    <div className="overflow-y-auto p-2">
                      <Markdown source={answer} />
                    </div>
                  )}
                </div>
              </div>
            </div>
            {/* <Divider /> */}
          </div>
        )}
        {step === 2 && (
          <div
            className="flex flex-col"
            style={{ width: size?.width, minHeight: size?.height, height: 'calc(80vh - 160px)' }}
          >
            {/* <Back onClick={() => setStep(1)} title="选择存放位置" /> */}
            <DatasetList onDatasetChange={setSelectedDataset} />
            {/* <Divider /> */}
          </div>
        )}
        <Drawer
          title="上下文"
          className="know-gov-drawer"
          placement="right"
          width={'50%'}
          onClose={() => {
            setHistoryOpen(false);
          }}
          open={historyOpen}
        >
          <div className="mt-4 h-full flex-1 rounded-lg border-2 border-WhiteSmoke bg-[#FFF] p-4">
            {qaList?.map((qa, index) => (
              <div key={index}>
                {qa.obj == 'Human' && (
                  <div className="ml-auto w-fit rounded-l-2xl rounded-t-2xl bg-[#6640FF] p-4 text-white">
                    <Markdown source={qa.content} />
                  </div>
                )}
                {qa.obj == 'AI' && <div>{answerRender(removeThinkTags(qa.content), false)}</div>}
              </div>
            ))}
          </div>
        </Drawer>
      </>
    );
  },
);

export default memo(QAView);
